﻿using KWT.DRG_DIP.API.Infrastructure;
using KWT.DRG_DIP.DB;
using KWT.DRG_DIP.DTO.Plugin;
using KWT.DRG_DIP.PO.Settlement;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace KWT.DRG_DIP.API.Controllers.Plugin
{
    /// <summary>
    /// 数据
    /// </summary>
    [AllowAnonymous]
    [ApiExplorerSettings(GroupName = "plugin")]
    public class DataController : PluginControllerBase
    {
        public EFContext ef { get; set; }

        /// <summary>
        /// 住院历史信息
        /// </summary>
        /// <param name="certNo">证件号码</param>
        /// <returns></returns>
        [HttpGet]
        public OutputResult History([FromQuery] string certNo)
        {
            var list = (from x in ef.Set<Sys_List>().AsQueryable()
                        join y in ef.Set<List_DiagInfo>().AsQueryable()
                         on x.ListID equals y.ListID
                        join z in ef.Set<List_BasicInfo>().AsQueryable()
                        on x.ListID equals z.ListID
                        where z.CertNo == certNo
                        orderby y.OutTime ascending
                        select new
                        {
                            OutTime=y.OutTime.ToString("yyyy-MM-ddTHH:mm:ss"),
                            y.InDays,
                            MainDiag = x.Diag_Code + " " + x.Diag_Name,
                            MainOper = x.Oper_Code + " " + x.Oper_Name,
                            GroupName = (string.IsNullOrEmpty(x.Assist_Code)? x.Group_Code: x.Group_Code+ "_"+ x.Assist_Code) 
                                    + " " + (string.IsNullOrEmpty(x.Assist_Name) ? x.Group_Name : x.Group_Name + "_" + x.Assist_Name)
                        }).AsNoTracking().ToList();
            return Output(true, "", "", list);
        }

        /// <summary>
        /// 保存分组结果
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public OutputResult Suggest(InSuggest dto)
        {
            var suggest = _mapper.Map<List_Suggest>(dto);
            if (ef.Set<List_Suggest>().Any(x => x.CertNo == dto.CertNo.Trim()))
            {
                var f = ef.Set<List_Suggest>().Where(x => x.CertNo == dto.CertNo.Trim()).ExecuteDelete() > 0;
            }
            if (string.IsNullOrEmpty(dto.LSID))
            {
                suggest.LSID = "LS" + snow_id.CreateId().ToString();
                ef.Add(suggest);
            }
            else
            {
                ef.Update(suggest);
            }
            var flag = ef.SaveChanges() > 0;
            return Output(flag, "操作成功", "操作失败");
        }
    }
}
